const app = getApp();
const batchUpload = require('../../utils/batchUpload.js');

Page({
  data: {
    date: '',
    scheduleList: [],
    showTypeModal: false,
    showEditModal: false,
    editType: null,
    editId: null,
    editHour: '08:00',
    editTitle: '',
    editImages: [],
    editLat: '',
    editLng: '',
    editRemark: '',
    rideList: [],
    rideIndex: 0,
    editRideId: null,
    userId: 1, // 可根据实际登录用户调整
    showGpxModal: false,
    gpxFile: null,
    gpxFileName: '',
    pendingGpxFile: null,
    showImgDeleteMode: false,
  },
  onLoad() {
    const now = new Date();
    const dateStr = `${now.getFullYear()}-${this.pad(now.getMonth()+1)}-${this.pad(now.getDate())}`;
    this.setData({ date: dateStr });
    this.getScheduleList();
  },
  onShow() {
    if (this.data.editType === 3) {
      this.loadRideList();
    }
    this.getScheduleList();
  },
  pad(n) { return n < 10 ? '0' + n : n; },
  onDateChange(e) {
    this.setData({ date: e.detail.value }, this.getScheduleList);
  },
  getScheduleList() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/trip/schedule/list`,
      method: 'GET',
      data: { userId: this.data.userId, date: this.data.date },
      success: res => {
        if (res.data && res.data.code === 200) {
          let list = (res.data.data || []).map(item => {
            const arr = item.imageUrls
              ? item.imageUrls.split(',').map(url =>
                  url.startsWith('http') ? url : `${app.globalData.baseUrl}${url}`
                )
              : [];
             // 类型映射
             let typeText = '';
             switch(Number(item.type)) {
               case 0: typeText = '酒店'; break;
               case 1: typeText = '饭店'; break;
               case 2: typeText = '景点'; break;
               case 3: typeText = '骑行'; break;
               default: typeText = '';
             }
             // 时间裁剪
             let timeText = item.datetime ? item.datetime.slice(11, 16) : '12:00';
            return {
              ...item,
              type: Number(item.type),
              typeText,
              timeText,
              imageUrlsArr: arr.length ? arr : [`/images/${item.type || 0}.jpg`]
            };
          });
          // 按时间升序排列
          list = list.sort((a, b) => (a.datetime > b.datetime ? 1 : -1));
          this.setData({ scheduleList: list });
        }
      }
    });
  },
  getTypeText(type) {
    switch(Number(type)) {
      case 0: return '酒店';
      case 1: return '饭店';
      case 2: return '景点';
      case 3: return '骑行';
      default: return '';
    }
  },
  onAdd() {
    this.setData({ showTypeModal: true });
  },
  onTypeSelect(e) {
    const type = Number(e.currentTarget.dataset.type);
    this.setData({
      showTypeModal: false,
      showEditModal: true,
      editType: type,
      editId: null,
      editHour: '08:00',
      editTitle: '',
      editImages: [],
      editLat: '',
      editLng: '',
      editRemark: '',
      editRideId: null,
      rideIndex: -1 // 默认未选路线
    });
    if (type === 3) {
      this.loadRideList();
    }
  },
  onTypeCancel() {
    this.setData({ showTypeModal: false });
  },
  onEdit(e) {
    const id = Number(e.currentTarget.dataset.id); // 强制转为数字
    const item = this.data.scheduleList.find(i => i.id === id);
    if (!item) return;
    const dt = new Date(item.datetime);
    this.setData({
      showEditModal: true,
      editType: item.type,
      editId: item.id,
      editHour: this.pad(dt.getHours()) + ':00',
      editTitle: item.title,
      editImages: item.imageUrlsArr || [],
      editLat: item.lat,
      editLng: item.lng,
      editRemark: item.remark,
      editRideId: item.rideId,
      rideIndex: 0
    });
    if (item.type === 3) {
      this.loadRideList(() => {
        const idx = this.data.rideList.findIndex(r => r.id === item.rideId);
        this.setData({ rideIndex: idx >= 0 ? idx : 0 });
      });
    }
  },
  onDelete(e) {
    const id = Number(e.currentTarget.dataset.id); // 强制转为数字
    wx.showModal({
      title: '确认删除？',
      success: res => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/trip/schedule/delete?id=${id}`,
            method: 'POST',
            success: () => {
              wx.showToast({ title: '已删除' });
              this.getScheduleList();
            }
          });
        }
      }
    });
  },
  onEditCancel() {
    this.setData({ showEditModal: false });
  },
  onEditTitle(e) {
    this.setData({ editTitle: e.detail.value });
  },
  onEditRemark(e) {
    this.setData({ editRemark: e.detail.value });
  },
  onHourChange(e) {
    this.setData({ editHour: e.detail.value });
  },
  onChooseImage() {
    wx.chooseImage({
      count: 9 - this.data.editImages.length,
      success: res => {
        batchUpload({
          url: `${app.globalData.baseUrl}/api/trip/schedule/upload`,
          files: res.tempFilePaths,
          name: 'files',
          formData: {},
          success: (res) => {
            // 只用后端返回的图片URL，渲染时拼接baseUrl
            const newUrls = res.data.map(url =>
              url.startsWith('http') ? url : `${app.globalData.baseUrl}${url}`
            );
            this.setData({ editImages: [...this.data.editImages, ...newUrls] });
          },
          fail: () => {
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        });
      }
    });
  },
  onChooseLocation() {
    wx.chooseLocation({
      success: res => {
        this.setData({
          editLat: res.latitude,
          editLng: res.longitude,
          editTitle: res.name || this.data.editTitle // 自动写入位置名称
        });
      },
      fail: err => {
        console.error('选点失败', err);
        wx.showToast({ title: '选点失败', icon: 'none' });
      }
    });
  },
  onDeleteImage(e) {
    e.stopPropagation && e.stopPropagation(); // 防止冒泡
    const idx = e.currentTarget.dataset.index;
    const images = [...this.data.editImages];
    images.splice(idx, 1);
    this.setData({ editImages: images });
  },
  onToggleImgDeleteMode() {
    this.setData({ showImgDeleteMode: !this.data.showImgDeleteMode });
  },
  onNav(e) {
    // 获取当前行数据
    const id = Number(e.currentTarget.dataset.id);
    const item = this.data.scheduleList.find(i => i.id === id);
    if (!item || !item.lat || !item.lng) {
      wx.showToast({ title: '无有效位置', icon: 'none' });
      return;
    }
    wx.openLocation({
      latitude: Number(item.lat),
      longitude: Number(item.lng),
      name: item.title || '',
      address: item.remark || '',
      scale: 16
    });
  },
  onPreviewImage(e) {
    // 支持swiper多图预览
    let urls = e.currentTarget.dataset.urls;
    let index = Number(e.currentTarget.dataset.index) || 0;
    if (!Array.isArray(urls)) {
      // 兼容单图
      if (typeof urls === 'string') urls = [urls];
      else urls = [];
    }
    if (!urls.length) {
      wx.showToast({ title: '无图片可预览', icon: 'none' });
      return;
    }
    wx.previewImage({
      urls: urls,
      current: urls[index] || urls[0]
    });
  },
  // 骑行相关
  loadRideList(cb) {
    wx.request({
      url: `${app.globalData.baseUrl}/api/gpx/info/list`,
      method: 'GET',
      success: res => {
        if (res.data && res.data.code === 200) {
          let list = (res.data.data || []).filter(r => (r.startTime || '').startsWith(this.data.date));
          // 追加“添加骑行路线”选项
          list.push({ id: -1, roadName: '➕ 添加骑行路线' });
          this.setData({ rideList: list }, () => { if (cb) cb(); });
        }
      }
    });
  },
  onRideChange(e) {
    const idx = Number(e.detail.value);
    const ride = this.data.rideList[idx];
    if (ride && ride.id === -1) {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['.gpx'],
        success: res => {
          const file = res.tempFiles[0];
          this.setData({
            showGpxModal: true,
            gpxFile: file,
            gpxFileName: file.name,
            pendingGpxFile: file
          });
        }
      });
      return;
    }
    this.setData({
      rideIndex: idx,
      editRideId: ride && ride.id !== -1 ? ride.id : null,
      editTitle: ride && ride.id !== -1 ? ride.roadName : '',
      editRemark: ride && ride.id !== -1 && ride.remark ? ride.remark : '',
      editLat: ride && ride.id !== -1 && ride.endLat ? Number(ride.endLat) : '',
      editLng: ride && ride.id !== -1 && ride.endLng ? Number(ride.endLng) : '',
      editImages: [],
      editHour: ride && ride.id !== -1 && ride.startTime ? (ride.startTime.length >= 16 ? ride.startTime.slice(11, 16) : '08:00') : '08:00'
    });
    // 选中路线后自动加载图片
    if (ride && ride.id !== -1) {
      wx.request({
        url: `${app.globalData.baseUrl}/api/gpx/image/list/${ride.id}`,
        method: 'GET',
        success: res => {
          if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
            const imgs = res.data.data.map(img => img.filename ? `${app.globalData.baseUrl}/uploads/img/${img.filename}` : '').filter(Boolean);
            this.setData({ editImages: imgs });
          }
        }
      });
    }
  },
  onInputGpxFileName(e) {
    this.setData({ gpxFileName: e.detail.value });
  },
  onCancelGpxModal() {
    this.setData({ showGpxModal: false, gpxFile: null, gpxFileName: '', pendingGpxFile: null });
  },
  onConfirmGpxModal() {
    let customName = this.data.gpxFileName.trim();
    if (!customName) customName = this.data.gpxFile.name;
    if (!customName.endsWith('.gpx')) customName += '.gpx';
    const file = this.data.pendingGpxFile;
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/api/gpx/upload`,
      filePath: file.path,
      name: 'file',
      formData: { filename: customName },
      success: uploadRes => {
        let filename = '', displayName = '', fileSize = '';
        try {
          const resObj = JSON.parse(uploadRes.data);
          if (resObj.code === 200 && resObj.data) {
            filename = resObj.data.filename || '';
            displayName = resObj.data.displayName || '';
            fileSize = resObj.data.fileSize || '';
          }
        } catch (e) {}
        this.setData({ showGpxModal: false, gpxFile: null, gpxFileName: '', pendingGpxFile: null });
        if (filename) {
          wx.navigateTo({
            url: `/pages/map/map?filename=${encodeURIComponent(filename)}&display_name=${encodeURIComponent(displayName)}&file_size=${encodeURIComponent(fileSize)}&from=schedule`
          });
        }
      }
    });
  },
  onEditRide() {
    const ride = this.data.rideList[this.data.rideIndex];
    if (ride && ride.id !== -1) {
      wx.navigateTo({ url: `/pages/gpxview/gpxview?id=${ride.id}&edit=1&from=schedule` });
    }
  },

  onEditConfirm() {
    // 组装数据
    const { date, editHour, editType, editTitle, editImages, editLat, editLng, editRemark, editRideId, editId, userId, rideList, rideIndex } = this.data;
    const datetime = `${date} ${editHour}:00`;
    const imageUrls = editImages.join(',');
    const data = {
      userId: Number(userId),
      datetime,
      type: Number(editType),
      title: editTitle,
      imageUrls,
      lat: editLat ? Number(editLat) : null,
      lng: editLng ? Number(editLng) : null,
      remark: editRemark,
      rideId: Number(editType) === 3 ? (editRideId || (rideList[rideIndex] && rideList[rideIndex].id)) : null,
      status: 0
    };
    if (editId) data.id = editId;
    // 移除无效字段
    if (!data.lat) delete data.lat;
    if (!data.lng) delete data.lng;
    if (!data.rideId) delete data.rideId;
    wx.request({
      url: `${app.globalData.baseUrl}/api/trip/schedule/${editId ? 'update' : 'add'}`,
      method: 'POST',
      data,
      header: { 'content-type': 'application/json' },
      success: () => {
        wx.showToast({ title: '已保存' });
        this.setData({ showEditModal: false });
        this.getScheduleList();
      }
    });
  },
  onRideMap(e) {
    const id = Number(e.currentTarget.dataset.id);
    const item = this.data.scheduleList.find(i => i.id === id);
    if (!item || !item.rideId) {
      wx.showToast({ title: '无骑行路线', icon: 'none' });
      return;
    }
    // 跳转到gpxview页面查看（edit=0, from=schedule）
    wx.navigateTo({
      url: `/pages/gpxview/gpxview?id=${item.rideId}&edit=0&from=schedule`
    });
  },
}); 